<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class Dialog extends Controller
{
    //
    private $push;
    public function __construct(){
    	$this->push = new \App\model\pushDataToDatabase();
    	date_default_timezone_set("Asia/Shanghai");
    }

    public function addTheCache(Request $request){
    	$message['sender_id'] = $request->input('sender', NULL);
    	$message['receiver_id'] = $request->input('getter', NULL);
        $message['type'] = $request->input('type',NULL);
    	$message['content'] = $request->input('message', NULL);
        $message['time'] = date("Y-m-d H:i:s");
    	if ($message['sender_id'] == NULL || $message['receiver_id'] == NULL || $message['content'] == NULL) {
    		$error['reason'] = 'There\'re need more key';
    		$error['code'] = 4;
    		return $error;
    	}
        $x = Redis::LPUSH($message['sender_id'].$message['receiver_id'].$message['type'], json_encode($message));
        $countKey = function(){
            $count = 0;
            foreach (Redis::keys('*') as $markDown => $cacheTitle) {
                $count += Redis::llen($cacheTitle);
            }
            return $count;
        };
        if ($countKey() >= 10) {
            $insertSuccess = function(){
                $count = 0;
                $contents = array();
                $data = 'init';
                foreach (Redis::keys('*') as $markDown => $cacheTitle) {
                    while (1) {
                        $data = Redis::Rpop($cacheTitle);
                        if ($data == false) {
                            break;
                        }
                        array_push($contents, json_decode($data,true));
                    }
                }
                foreach ($contents as $key => $value) {
                    if (!$this->push->pushTheData('nots', $value, $value['sender_id'].$value['receiver_id'])) {
                        return 0;
                    }
                }
                return 1;
            };
            if ($insertSuccess() == 1) {
                Redis::flushall();
                return 1;
            }else{
                $error['code'] = 6;
                $error['reason'] = 'Insert the chat cache false';
                return $error;
            }
        }
    }
}